package com.fight.strive.sys.modules.exception;

import com.fight.strive.sys.modules.exception.exceptions.StriveAccessDeniedException;
import com.fight.strive.sys.modules.exception.exceptions.StriveInvalidTokenException;
import com.fight.strive.sys.modules.common.ReStatus;
import com.fight.strive.sys.modules.exception.exceptions.StriveValidException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@RestControllerAdvice
public class GlobalHandler {

    @ExceptionHandler({Exception.class})
    public ReStatus<Void> handler(HttpServletRequest request,
                                  HttpServletResponse response,
                                  Exception e) {
        if (e instanceof StriveException
                || e instanceof StriveValidException) {
            // 已知异常，打印描述信息
            return ReStatus.failure(e.getMessage());
        } else if (e instanceof StriveInvalidTokenException) {
            // 无效的token，需要认证
            return ReStatus.invalidToken();
        } else if (e instanceof StriveAccessDeniedException) {
            // token有效，接口无权访问
            return ReStatus.accessDenied();
        } else {
            // 未知异常，打印详细异常堆栈
            log.error("请求地址：{}", request.getServletPath());
            log.error("异常：", e);
            return ReStatus.failure("未知错误：".concat(e.getMessage()));
        }
    }
}
